# -*- coding: utf-8 -*-
"""
TimeTracker v6.0 主入口 —— 纯 Qt6 版（无 pystray）
"""
import atexit
import threading
import time
import faulthandler, traceback, sys, os
from PyQt6.QtWidgets import QApplication, QSystemTrayIcon
from ui.qt6_tray_app import create_qt_tray_app
from ui.qt6_float_window import create_float_window, update_float_color
from utils.constants import GIT_SYNC_INTERVAL

# 修复 stderr/stdout 为 None 的问题
if sys.stderr is None:
    sys.stderr = open(os.devnull, 'w')
if sys.stdout is None:
    sys.stdout = open(os.devnull, 'w')

# 安全异常钩子
def safe_excepthook(*args):
    try:
        traceback.print_exception(*args, file=sys.stderr)
        if sys.stderr and hasattr(sys.stderr, 'flush'):
            sys.stderr.flush()
    except:
        pass

sys.excepthook = safe_excepthook

# 安全启用错误处理
try:
    faulthandler.enable()
except Exception:
    pass

# ---------- 模块路径 ----------
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'core'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'utils'))

# ---------- 业务模块 ----------
from services.system_utils import (
    setup_environment, safe_exit, sync_worker, verify_and_clean_old_files,
    ensure_early_startup, create_logon_task_xml, set_data_dir
)
from services.state_manager import (
    init_state_manager, set_initial_state, start_background_threads, set_state
)
from services.file_operations import init_file_operations
from utils.logger import log
from utils.input_dialogs import get_user_id
from git_sync import GitSyncManager
from core.signal_hub import add_state_listener, register_update_callback
from update import do_update

# ---------- 全局变量 ----------
_DATA_DIR = None
_USER_ID = None
_SYNC_ENABLED = False
git_mgr: GitSyncManager | None = None
qt_float_win = None
qt_tray = None

# ---------- 工具函数 ----------
def check_first_run():
    first_run_file = os.path.join(_DATA_DIR, '.first_run')
    if not os.path.exists(first_run_file):
        with open(first_run_file, 'w') as f:
            f.write('1')
        return True
    return False

def setup_git_sync():
    global git_mgr, _SYNC_ENABLED
    try:
        log('[GIT] 初始化 Git 同步...')
        git_mgr = GitSyncManager(_DATA_DIR, _USER_ID)
        _SYNC_ENABLED = git_mgr.enabled
    except Exception as e:
        log(f'[ERR] Git 同步初始化失败: {e}')
        _SYNC_ENABLED = False
    log(f'[MAIN] Git 推送周期已固定为 {GIT_SYNC_INTERVAL // 60} 分钟')
    
def setup_git_sync():
    global git_mgr, _SYNC_ENABLED
    try:
        log('[GIT] 初始化 Git 同步...')
        git_mgr = GitSyncManager(_DATA_DIR, _USER_ID)
        _SYNC_ENABLED = git_mgr.enabled
        
        # ★★★ 新增：如果是管理员，显示特殊提示
        if _USER_ID.lower().startswith("admin"):
            log('[ADMIN] 管理员模式已启用，可使用管理员汇总功能')
            
    except Exception as e:
        log(f'[ERR] Git 同步初始化失败: {e}')
        _SYNC_ENABLED = False
    log(f'[MAIN] Git 推送周期已固定为 {GIT_SYNC_INTERVAL // 60} 分钟')

def _delayed_update_check():
    time.sleep(5)
    if hasattr(_delayed_update_check, '_checked'):
        return
    _delayed_update_check._checked = True
    try:
        need_restart = do_update()
        if need_restart:
            log('[UPD] 更新已启动，准备退出当前进程')
            qt_tray.showMessage(
                "自动更新",
                "更新已开始，程序将在30秒内重启",
                QSystemTrayIcon.MessageIcon.Information,
                3000
            )
            time.sleep(3)
            from services.system_utils import _start_updater_and_exit
            _start_updater_and_exit()
    except Exception as e:
        log(f'[UPD] 更新检查异常: {e}')

import atexit
import threading

# 添加一个退出标志
_app_exiting = False

def safe_exit_wrapper():
    global _app_exiting
    if not _app_exiting:
        log('[MAIN] 正常退出流程，调用 safe_exit')
        safe_exit(None)
    else:
        log('[MAIN] 程序已标记为退出，跳过 safe_exit')

# ---------- 主入口 ----------
def main():
    global _DATA_DIR, _USER_ID, _SYNC_ENABLED, qt_float_win, qt_tray,_app_exiting

    try:
        # 0. 环境
        _DATA_DIR = setup_environment()
        from services.system_utils import set_data_dir
        set_data_dir(_DATA_DIR)

        # ★★★ 新增：初始化历史记录管理器
        from ui.qt6_input_dialog import init_history_manager
        init_history_manager(_DATA_DIR)
        
        # 1. 初始化
        verify_and_clean_old_files()
        atexit.register(safe_exit_wrapper)

        # 2. 首次运行
        if _DATA_DIR.startswith('D:\\') and check_first_run():
            log('[INFO] 首次运行，设置开机启动')
            from services.system_utils import ensure_early_startup, create_logon_task_xml
            ensure_early_startup()
            create_logon_task_xml()

        # 3. 用户 ID
        _USER_ID = get_user_id(_DATA_DIR)
        log('[INFO] 用户ID: ' + _USER_ID)

        # 4. Git 同步
        setup_git_sync()
        log(f'[INFO] Git同步状态: {_SYNC_ENABLED}')

        # 5. 业务模块
        init_state_manager(_DATA_DIR, _USER_ID)
        init_file_operations(_DATA_DIR, _USER_ID)
        set_initial_state(_USER_ID)

        # 调试：检查初始状态
        from services.state_manager import state as current_state

        # 手动触发一次颜色更新
        from core.signal_hub import fire_state_changed
        fire_state_changed(current_state)
  

        # ★★★ 新增：启动后台线程
        from services.state_manager import start_background_threads
        start_background_threads()

        # 6. Qt6 应用对象（必须最先创建）
        app = QApplication.instance() or QApplication(sys.argv)

        # 7. Qt6 悬浮窗（在 QApplication 之后）
        qt_float_win = create_float_window(_DATA_DIR, _USER_ID)
        log('[Qt6] 悬浮窗已启动')

        # 8. Qt6 托盘图标（在 QApplication 之后）
        from ui.qt6_tray_app import create_qt_tray_app
        qt_tray = create_qt_tray_app(_DATA_DIR, _USER_ID)
        log('[Qt6] 托盘已启动')

        # 9. 状态联动
        add_state_listener(update_float_color)      # 悬浮窗
        # 托盘的状态监听已经在 QtTrayApp 初始化时注册了

        # 10. 延迟触发初始颜色更新（确保Qt组件已完全初始化）
        def delayed_color_update():
            from services.state_manager import state as current_state
            from core.signal_hub import fire_state_changed
            fire_state_changed(current_state)

        # 使用QTimer在事件循环开始后触发
        from PyQt6.QtCore import QTimer
        QTimer.singleShot(100, delayed_color_update)  # 100ms后触发

        # 11. 延迟更新检查
        threading.Thread(target=_delayed_update_check, daemon=True).start()

        # 12. 进入 Qt 主循环
        log('[INFO] Qt6 主循环启动')
        exit_code = app.exec()
        
        # 标记程序正常退出
        _app_exiting = True
        log(f'[INFO] Qt 主循环结束，退出码: {exit_code}')
        sys.exit(exit_code)
        
    except Exception as e:
        log(f'[CRASH] 启动阶段崩溃: {e}')
        traceback.print_exc()
        _app_exiting = True
        # 不调用safe_exit，让程序继续运行
        log('[INFO] 程序从错误中恢复，继续运行')

if __name__ == '__main__':
    main()